package com.xuecheng.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.AuthApplication;
import com.xuecheng.ucenter.feignclient.CheckCodeClient;
import com.xuecheng.ucenter.mapper.XcUserMapper;
import com.xuecheng.ucenter.model.dto.AuthParamsDto;
import com.xuecheng.ucenter.model.dto.XcUserExt;
import com.xuecheng.ucenter.model.po.XcUser;
import com.xuecheng.ucenter.service.AuthService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @ClassName PasswordAuthServiceImpl
 * @Description 密码认证实现
 * @Date 2023/6/27 16:23
 * @Version 1.0
 */
@Service("password_authservice")
public class PasswordAuthServiceImpl implements AuthService {

    @Autowired
    XcUserMapper xcUserMapper;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    CheckCodeClient checkCodeClient;

    @Override
    public XcUserExt execute(AuthParamsDto authParamsDto) {
        //账号
        String username = authParamsDto.getUsername();
        //根据 username 账号查询数据库
        XcUser xcUser = xcUserMapper.selectOne(new LambdaQueryWrapper<XcUser>().eq(XcUser::getUsername, username));
        if (xcUser == null) {
            //查询到用户不存在，要返回 null 即可，spring security 框架抛出异常用户不存在
            throw new RuntimeException("账号不存在！");
        }

        //调用远程服务来校验验证码
        String checkcodeKey = authParamsDto.getCheckcodekey();
        String checkcode = authParamsDto.getCheckcode();
        if (StringUtils.isEmpty(checkcodeKey) || StringUtils.isEmpty(checkcode)) {
            throw new RuntimeException("请输入验证码！");
        }
        Boolean res = checkCodeClient.verify(checkcodeKey, checkcode);
        if (res == null || !res) {
            throw new RuntimeException("验证码输入错误！");
        }

        //加密后的正确的密码
        String passwordDb = xcUser.getPassword();
        //用户输入的密码
        String passwordForm = authParamsDto.getPassword();
        //校验密码
        boolean matches = passwordEncoder.matches(passwordForm, passwordDb);
        if (!matches) {
            throw new RuntimeException("账号或密码错误！");
        }

        XcUserExt xcUserExt = new XcUserExt();
        BeanUtils.copyProperties(xcUser, xcUserExt);
        return xcUserExt;
    }
}
